
//normal， new，hot，maintain
export const ServerState = {
    Normal: 'normal',
    New: 'new',
    Hot: 'hot',
    Maintain: 'maintain'
}

import { Component, director, _decorator } from 'cc';
import { wechat } from '../Network/Wechat';
import { GLoginState, GNetCmd, GNetConst } from '../Constans/Conf1';
import { GameStorage } from '../Data/GameStorage';
import { WmSocket } from '../Network/Wmsocket';
const { ccclass, property } = _decorator;

@ccclass('ServerCtr')
export default class ServerCtr extends Component {

    private static instance: ServerCtr = null!;

    public static GetInstance() {
        if (!this.instance) {
            this.instance = new ServerCtr();
            this.instance.InitServerCtr();
        }
        return this.instance;
    }
    serverId: number = 1;
    account: string = '';
    password: string = 'hsmnq2021';
    authCode: string = "";
    token: string = '';
    regionDataList: any[] = [];
    uid: string = '';
    regionId: string = '';
    nickName: string = '测试账号';
    isLogin: boolean = false;
    avatar: string = '';
    loginState: GLoginState = GLoginState.noYet; //服务端是否加载完成,有账号登录，无账号登录
    serverDataVersion: number = 0  //服务端的版本号
    serverData: any = {} //服务端数据

    // regions":{"1":"{\"id\":\"1\",\"name\":\"先行服\"}","2":"{\"id\":\"2\",\"name\":\"圣魂村\"}"},
    // "servers":{"1":"{\"id\":\"1\",\"name\":\"先行服1\",\"region\":\"1\",\"status\":\"normal\",\"years\":\"2021-07-21 08:00:00\"}",
    // "2":"{\"id\":\"2\",\"name\":\"先行服2\",\"region\":\"1\",\"status\":\"normal\",\"years\":\"2021-07-21 09:00:00\"}",
    // "3":"{\"id\":\"3\",\"name\":\"圣魂村1\",\"region\":\"2\",\"status\":\"normal\",\"years\":\"2021-07-21 10:00:00\"}",
    // "4":"{\"id\":\"4\",\"name\":\"圣魂村2\",\"region\":\"2\",\"status\":\"normal\",\"years\":\"2021-07-21 11:00:00\"}",
    // "5":"{\"id\":\"5\",\"name\":\"圣魂村3\",\"region\":\"2\",\"status\":\"normal\",\"years\":\"2021-07-21 12:00:00\"}","isUpdated":"0"}
    regionList: any = {};
    serverList: any = {};

    InitServerCtr() {
        this.account = GameStorage.getStringDisk('login_account', '');
        this.password = GameStorage.getStringDisk('login_password', this.password);
        this.authCode = GameStorage.getStringDisk('login_authCode', this.authCode);
        this.serverId = parseInt(GameStorage.getStringDisk('login_serverId', ""));

        director.on(GNetCmd.GetInviteCode.toString(), this.onMessageEvent, this);
    }

    //数据版本设置
    get dataVersion() {
        return GameStorage.getInt("dataVersion", 0)
    }
    set dataVersion(val: number) {
        if (val > this.dataVersion) {
            GameStorage.setInt("dataVersion", val)
        }
    }
    addDataVersion(val: number = 1) {
        GameStorage.setInt("dataVersion", GameStorage.getInt("dataVersion", 0) + val)
    }

    CheckIsHaveAccount() {
        if (!this.account || this.account == '') {
            // 没有账号
            return false;
        }
        return true;
    }

    CheckHaveDataById(regionId: number) {
        for (let i = 0; i < this.regionDataList.length; i++) {
            const data = this.regionDataList[i];
            if (data.regionId == regionId) {
                return true;
            }
        }
        return false;
    }

    get Account() {
        return this.account;
    }

    set Account(str: string) {
        this.account = str;
        GameStorage.setStringDisk('login_account', this.account);
    }

    get PassWord() {
        return this.password;
    }

    set PassWord(str: string) {
        this.password = str;
        GameStorage.setStringDisk('login_password', this.password);
    }
    get AuthCode() {
        return this.authCode;
    }

    set AuthCode(str: string) {
        this.authCode = str;
        GameStorage.setStringDisk('login_authCode', this.authCode);
    }

    get ServerId() {
        return this.serverId;
    }
    set ServerId(id: number) {
        this.serverId = id;
        GameStorage.setStringDisk('login_serverId', this.serverId + "");
    }

    UpdateRegions(regions: any) {
        for (const key in regions) {
            const data = regions[key];
            this.regionList[key] = JSON.parse(data);
        }
    }

    UpdateServers(servers: any) {
        for (const key in servers) {
            const data = servers[key];

            this.serverList[key] = JSON.parse(data);
            // if (gl.debug) {
            //     switch (Number(this.serverList[key].id)) {
            //         case 1:
            //             this.serverList[key].status ='maintain'; 
            //             break;
            //         case 2:
            //             this.serverList[key].status = 'hot';
            //             break;
            //         case 5:
            //             this.serverList[key].status = 'new';
            //             break;
            //         default:

            //             break;
            //     }
            // }

        }
    }

    public GetServerData(serverId: number) {
        for (const key in this.serverList) {
            const data = this.serverList[key];
            if (data.id == serverId) {
                return data;
            }
        }
        return null;
    }
    public GetStateIcon(status: string) {
        switch (status) {
            case ServerState.Normal:
                return;
            case ServerState.New:
                return 'fm_tb_xin';
            case ServerState.Hot:
                return 'fm_tb_bao';
            case ServerState.Maintain:
                return 'fm_tb_wei';
            default:
                break;
        }
    }

    // 获取最新的不在维护中服务器
    public GetLastNewServer() {
        let id = 1;
        for (const key in this.serverList) {
            const data = this.serverList[key];
            let did = Number(data.id)
            if (did > id && data.status != ServerState.Maintain) {
                id = did;
            }
        }
        return id;
    }

    public reqConnect() {
        WmSocket.getInstance().connect();
    }

    public reqRegister(account: any, password: any) {
        let data = {
            "cmd": GNetCmd.UserRegister,
            "lang": "zh",
            "account": account,
            "password": password,
        }
        WmSocket.getInstance().send({ "data": data });
    }

    public reqLogin() {
        let data = {
            "cmd": GNetCmd.UserLogin,
            "lang": "zh",
            "account": this.account,
            "password": this.password,
            'nickName': this.nickName + this.account
        }
        WmSocket.getInstance().send({ "data": data });
    }

    public reqLoginByAccount(account: string, password: string, authCode: string) {
        let data = {
            "cmd": GNetCmd.UserLogin,
            "lang": "zh",
            "account": account,
            "password": password,
            "authCode": authCode,
            'nickName': this.nickName + this.account
        }
        WmSocket.getInstance().send({ "data": data });
    }

    public reqRegionList() {
        let data = {
            "cmd": GNetCmd.GetRegionList,
            "lang": "zh",
            "token": this.token,
        }
        WmSocket.getInstance().send({ "data": data });
    }

    public reqRegionData() {
        // if (!this.ServerId || this.ServerId == 0) {
        //     // Notifications.emit(GDef.wdEvent.showTip, {msg:'请选择区服'})
        //     return;
        // }
        this.ServerId = 1 //默认选一个区服
        let data = {
            "cmd": GNetCmd.GetRegionData,
            "lang": "zh",
            "token": this.token,
            "version": ServerCtr.GetInstance().dataVersion,
            "regionId": this.ServerId.toString()
        }
        console.log("发送服务端数据请求---11", data)
        WmSocket.getInstance().send({ "data": data });
    }

    //好友链接登录后，调用此接口建立关联关系
    public reqSetFriendCode(shareUserId: string) {
        if (ServerCtr.GetInstance().loginState != GLoginState.loginWithAccount) {
            return
        }
        let data = {
            "cmd": GNetCmd.SetFriendCode,
            "lang": "zh",
            "token": this.token,
            "InviteCode": shareUserId,
        }
        console.log("发送服务端数据请求 -- 设置好友邀请码---11", data)
        // var m = map[string]interface{}{ //不需要处理返回
        //     "cmd":    proto.SetFriendCode,
        //     "status": util.RES_MSG_SUCCESS,
        // }
        WmSocket.getInstance().send({ "data": data });
    }

    //获得好友功能相关数据
    public reqGetFriendVal() {
        if (ServerCtr.GetInstance().loginState != GLoginState.loginWithAccount) {
            return
        }
        let data = {
            "cmd": GNetCmd.GetFriendVal,
            "lang": "zh",
            "token": this.token,
            "keys": "friendPassCnt,videoCalCnt", //相关参数
            "rules": "total,total", //相关规则
        }
        console.log("发送服务端数据请求 -- 获得好友功能相关数据---11", data)
        // { 返回值参考
        //     "cmd":        proto.SetFriendCode,
        //     "friendCnt":  cnt,
        //     "friendData": util.MapToJSONF(dataMap),
        //     "status":     util.RES_MSG_SUCCESS,
        // }
        WmSocket.getInstance().send({ "data": data });
    }

    public onMessageEvent(value: any) {
        if (value) {
            console.log("处理分享的消息:", value);
            if (value.status != GNetConst.ResSuccess) {
                console.error("服务端响应失败~!")
                return;
            }
        }
    }


    // public reqUploadOldPlayerData(isFirst:boolean = true){
    //     if(Const.isActiveMemoryTmp) return
    //     let datas = GameStorage.getAll(isFirst);
    //     // 大数据拆分
    //     console.log("大数据要拆分开....:",datas);

    //     // 全部发送上传
    //     for (const key in datas) {
    //         const value = datas[key];
    //         // cc.sys.localStorage.setItem(key,value);
    //         this.reqCloudSaveManual(key,value,true);
    //     }
    // }

    public reqCloudSaveManual(key: string, val: any) {
        // CronCtr.getInstance().cloudSaveManual(key,val);
    }

    public wxLoginBegin(failCb?: Function) {
        wx.login({
            success(loginResult) {
                console.warn("-----微信登录--", loginResult);
                let data = {
                    "cmd": GNetCmd.ReqWxSession,
                    "lang": "zh",
                    "channel": "wx",
                    "nickName": "",
                    jscode: loginResult.code,
                };
                console.warn('发送登录数据：', data);
                WmSocket.getInstance().send({ "data": data });
            },
            fail(res) {
                let msg = "登录失败：" + res.errMsg;
                if (failCb) failCb(msg);
            }
        });
        return;

        wechat.wxGetSetting().then((res: any) => {
            //授权登录，走流程
            console.warn("微信授权结果12---", res, res['userInfo'])
            if (res.hasOwnProperty("userInfo")) {
                ServerCtr.GetInstance().wxLogin() //第一次授权
            }
            if (res.hasOwnProperty("authSetting")) {
                let authSetting = res.authSetting;
                if (authSetting['scope.userInfo']) {//第二次授权
                    ServerCtr.GetInstance().wxLogin()
                }
            }

        }).catch((res) => {
            //没有授权，直接登录
            console.warn("没有账号登录---",)
            this.loginState = GLoginState.loginWithoutAccount
        })
    }

    public wxLogin() {
        //新方案
        wechat.getWxLoginResult((err: any, loginResult: any) => {
            if (err) {
                // EventMgr.getInstance().event('tipshow', '获取用户信息失败');
                // App.ui.ShowPanel("WxScopeTipsPanel");
                console.error('登录数据err：', loginResult);
                return;
            }
            console.log('登录数据info：', loginResult);
            this.nickName = loginResult.userInfo.nickName;
            this.avatar = loginResult.userInfo.avatarUrl;
            // let wxEncrypted = loginResult.encryptedData;
            // let wxIv = loginResult.iv;
            // let wxCode = loginResult.code;
            // let wxUserInfo = loginResult.userInfo;
            let data = {
                "cmd": GNetCmd.ReqWxSession,
                "lang": "zh",
                "channel": "wx",
                jscode: loginResult.code,
                nickName: this.nickName,
                // wcencrypted: loginResult.encryptedData,
                // wciv: loginResult.iv
            };
            console.warn('发送登录数据：', data);
            WmSocket.getInstance().send({ "data": data });
        });
    }

    public UnloadAvatarUrl() {
        let data = {
            "cmd": GNetCmd.UploadAvatar,
            "lang": "zh",
            "token": this.token,
            "avatar": this.avatar,
        }
        WmSocket.getInstance().send({ "data": data });
    }
}
